from .models import Article, Column, Topic
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from django.views.generic import ListView, DetailView
from .serializers import ArticleSerializer, ColumnSerializer, TopicSerializer

class ArticleListView(ListView):
    model = Article
    template_name = 'django_article_app/article_list.html'
    context_object_name = 'articles'
    paginate_by = 10

    def get_queryset(self):
        queryset = Article.objects.filter(status='published').order_by('-publish_date')
        column_slug = self.request.GET.get('column')
        if column_slug:
            queryset = queryset.filter(column__slug=column_slug)
        return queryset

class ArticleDetailView(DetailView):
    model = Article
    template_name = 'django_article_app/article_detail.html'
    context_object_name = 'article'

class ColumnListView(ListView):
    model = Column
    template_name = 'django_article_app/column_list.html'
    context_object_name = 'columns'

class ColumnDetailView(DetailView):
    model = Column
    template_name = 'django_article_app/column_detail.html'
    context_object_name = 'column'
    slug_field = 'slug'
    slug_url_kwarg = 'slug'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['articles'] = Article.objects.filter(
            column=self.object, status='published'
        ).order_by('-publish_date')
        return context
from django.shortcuts import render

# Create your views here.

# API视图集
class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

class ColumnViewSet(viewsets.ModelViewSet):
    queryset = Column.objects.all()
    serializer_class = ColumnSerializer
    


class TopicViewSet(viewsets.ModelViewSet):
    queryset = Topic.objects.all()
    serializer_class = TopicSerializer